<template>
  <div class="data-visualiztion">
    <!-- synthetical -->
    <section v-if="activeTab == 'synthetical'" class="tab-page tl-box-shadow">
      <template v-if="showChart">
        <transition
          appear
          name="animate__animated animate__bounce"
          enter-active-class="animate__slideInLeft"
        >
          <div class="left-chart" :style="chartBoxStyle.syntheticalLeftBox">
            <Synthetical />
          </div>
        </transition>
      </template>
      <template v-if="customSyntheticalVisible">
        <CustomSynthetical />
      </template>
      <template v-if="showCustomSyntheticalEdit">
        <CustomSyntheticalEdit :village="currentVillage" />
      </template>
    </section>

    <!-- flow -->
    <section v-if="activeTab == 'flow'" class="tab-page tlr-box-shadow">
      <transition
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__slideInLeft"
      >
        <div class="left-chart" :style="chartBoxStyle.flowLeftBox">
          <FlowLeft />
        </div>
      </transition>
      <transition
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__slideInRight"
      >
        <div class="right-chart" v-if="!isMobile">
          <FlowRight />
        </div>
      </transition>
    </section>
    <!-- rentControl -->
    <section v-if="activeTab == 'rentControl'" class="tab-page page-mask">
      <RentControl />
    </section>
    <!-- centerControl -->
    <section v-if="activeTab == 'centerControl'" class="tab-page page-mask">
      <CenterControl />
    </section>
    <!-- security -->
    <section v-if="activeTab == 'security'" class="tab-page tlr-box-shadow">
      <transition
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__slideInLeft"
      >
        <div class="left-chart" :style="chartBoxStyle.flowLeftBox">
          <SecurityLeft />
        </div>
      </transition>
      <transition
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__slideInRight"
      >
        <div class="right-chart" v-if="!isMobile">
          <SecurityRight />
        </div>
      </transition>
      <transition
        appear
        name="animate__animated animate__bounce"
        enter-active-class="animate__slideInUp"
      >
        <div class="bottom-chart" v-if="!isMobile">
          <SecurityBottom />
        </div>
      </transition>
    </section>

    <!-- components show in every tab page -->
    <template v-if="isTabPage">
      <!-- common header -->
      <section class="page-header">
        <VillageInfo @change="villageChangeHandler" @refresh="initData" />
        <WeatherInfo />
      </section>
      <!-- 3d model  -->
      <section class="model-box">
        <div
          class="map-container"
          ref="mapContainer"
          v-if="showMapContainer"
        ></div>
        <template v-if="showCanvasContainer">
          <CanvasBackground
            :village="currentVillage"
            @showBuildInfoComponent="showBuildInfoComponent"
            @onBuildChange="onBuildChange"
            @showMonitorModal="getMonitorInfo"
          />
        </template>
      </section>
      <!-- tabs -->
      <section class="tab-list">
        <div class="preview-mode">
          <a-popover trigger="click" v-model:visible="previewPopVisible">
            <template #content>
              <a-row
                type="flex"
                justify="space-between"
                align="middle"
                style="width: 160px"
                v-if="!isViewClosure"
              >
                <a-col>预览模式</a-col>
                <a-col>
                  <a-switch
                    checked-children="开"
                    un-checked-children="关"
                    :checked="previewStatus"
                    @change="handlePreviewModeChange"
                  />
                </a-col>
              </a-row>
              <a-row
                type="flex"
                justify="space-between"
                align="middle"
                style="width: 160px; margin-top: 1rem"
              >
                <a-col>展示组件</a-col>
                <a-col>
                  <a-switch
                    checked-children="开"
                    un-checked-children="关"
                    :checked="customSyntheticalVisible"
                    @change="customSyntheticalVisibleChange"
                  />
                </a-col>
              </a-row>
              <a-row
                type="flex"
                justify="end"
                align="middle"
                style="width: 160px; margin-top: 1rem"
                v-if="isSuperAdmin && !isViewClosure"
              >
                <a-col>
                  <a-checkbox
                    v-model:checked="hiddenPreviewBtn"
                    @change="handlePreviewModeHidden"
                  >
                    隐藏数据预览
                    <text-tip :tips="['关闭后对所有成员生效，不可恢复']" />
                  </a-checkbox>
                </a-col>
              </a-row>
            </template>
            <span
              class="round-button"
              :class="{ 'gray-button': !previewStatus }"
              @click="previewPopVisible = !previewPopVisible"
              v-if="!hiddenPreviewBtn"
            >
              页面设置
            </span>
          </a-popover>
        </div>
        <div v-if="isMobile">
          <a-dropdown placement="topCenter">
            <div class="tab-item">
              <span>{{ currentTab.title }}</span>
              <SwapOutlined class="ml-4" />
            </div>
            <template #overlay>
              <a-menu @click="(e) => tabChangeHandler(e.key)">
                <a-menu-item
                  v-for="tab of tabList"
                  :key="tab.key"
                  class="text-center"
                  :class="{ 'text-primary': tab.key == activeTab }"
                >
                  {{ tab.title }}
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </div>
        <div v-for="tab of tabList" :key="tab.key" class="tab-item" v-else>
          <span
            class="item"
            :class="{ 'active-tag': tab.key == activeTab }"
            @click="tabChangeHandler(tab.key)"
          >
            {{ tab.title }}
          </span>
        </div>
        <!-- building tag -->
        <div class="building-tag">
          <span class="round-button" @click.stop="chooseBuildingHandler">
            {{ currentBuilding.build_name || "指定楼宇" }}
          </span>
        </div>
      </section>
    </template>

    <!-- modal -->
    <!-- choose villages or buildings -->
    <DataFrom
      :visible="showSwitchModal"
      :canCancel="modalCanCancel"
      :type="changeType"
      @success="changeDataFromSuccess"
      @cancel="showSwitchModal = false"
    />

    <!-- 楼宇：实景图 -->
    <BuildRealPic
      :visible="buildRealPicVisible"
      :buildDetail="buildInfo"
      @onClose="onBuildRealPicClose"
    />

    <!-- 楼宇：介绍 -->
    <BuildRichText
      :visible="buildRichTextVisible"
      :buildDetail="buildInfo"
      @onClose="onBuildRichTextClose"
    />

    <!-- 楼宇：剖面图 -->
    <BuildSection
      :visible="buildSectionVisible"
      :buildDetail="currentBuilding"
      @onClose="onBuildSectionClose"
    />

    <!-- 视频监控 -->
    <MonitorModal
      :visible="monitorModalVisible"
      :videoInfo="currentMonitorVideo"
      @onClose="onMonitorModalClose"
    />
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
  watch,
  h,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import common from "./utils/common";
import utils from "../../common/utils/utils";
import store from "../../store";
import SocketService from "./utils/websocket";
import DataFrom from "./modules/DataFrom.vue";
import VillageInfo from "./modules/VillageInfo.vue";
import WeatherInfo from "./modules/WeatherInfo.vue";
// 综合态势
import Synthetical from "./modules/synthetical/index.vue";
// 流量分析
import FlowLeft from "./modules/flow/left.vue";
import FlowRight from "./modules/flow/right.vue";
// 租控管理
import RentControl from "./modules/rentControl/index.vue";
// 智能中控
import CenterControl from "./modules/centerControl/index.vue";
import { message, Modal } from "ant-design-vue";
import { SwapOutlined } from "@ant-design/icons-vue";
import request from "../../common/utils/request";
import BuildRealPic from "./modules/BuildComponents/BuildRealPic.vue";
import BuildRichText from "./modules/BuildComponents/BuildRichText.vue";
import BuildSection from "./modules/BuildComponents/BuildSection.vue";

import CanvasBackground from "./modules/CanvasBackground.vue";
import CustomSynthetical from "./modules/CustomSynthetical/index.vue";
import CustomSyntheticalEdit from "./modules/CustomSynthetical/edit.vue";

// 安防动态
import SecurityLeft from "./modules/security/left.vue";
import SecurityRight from "./modules/security/right.vue";
import SecurityBottom from "./modules/security/bottom.vue";
import MonitorModal from "./modules/security/components/MonitorModal.vue";
let mapInstance, mapMonitorMarkers, mapBuildMarkers;

import { TextTip } from "bl-common-vue3";

export default defineComponent({
  name: "DataVisualization",
  components: {
    DataFrom,
    VillageInfo,
    WeatherInfo,
    Synthetical,
    FlowLeft,
    FlowRight,
    RentControl,
    CenterControl,
    SwapOutlined,
    BuildRealPic,
    BuildRichText,
    BuildSection,

    CanvasBackground,
    CustomSynthetical,
    CustomSyntheticalEdit,

    SecurityLeft,
    SecurityRight,
    SecurityBottom,
    MonitorModal,

    TextTip,
  },
  setup() {
    const route = useRoute();
    const router = useRouter();

    const chartBoxStyle = reactive({
      syntheticalLeftBox: {
        width: "54rem",
      },
      flowLeftBox: {},
    });

    const state = reactive({
      // tabs
      tabList: BOTTOM_TAB_LIST,
      loadedTabKeys: [],
      activeTab: "",
      // switch villages or buildings
      showSwitchModal: false,
      changeType: "village",
      modalCanCancel: false,
      villageList: [],
      currentVillage: {},
      currentBuilding: {},
      // websocket
      socketServe: SocketService.Instance,
      // map
      mapContainer: null,
      showMapContainer: false,
      // chart
      showChart: false,
      // preview
      previewPopVisible: false,
      hiddenPreviewBtn: false,
      // 2D鸟瞰图
      showCanvasContainer: false,
      buildRealPicVisible: false,
      buildRichTextVisible: false,
      buildSectionVisible: false,
      buildInfo: {},
      // 自定义组件
      customSyntheticalVisible: false, //展示自定义综合态势
      showCustomSyntheticalEdit: false, //展示自定义综合态势:编辑模式

      monitorModalVisible: false,
      currentMonitorVideo: [],
      monitorDataList: [],
      isViewClosure: false, // 预览按钮是否永久关闭

      currentAddress: {}, // 选中地址
      addressList: [],
      geocoder: null,
    });

    const isTabPage = computed(() => TAB_KEYS.includes(state.activeTab));
    const currentTab = computed(() =>
      BOTTOM_TAB_LIST.find((item) => item.key == state.activeTab)
    );
    const previewStatus = computed(() => store.getters.dataVPreview);

    // click event
    const tabChangeHandler = (key) => {
      if (state.activeTab == key) {
        return;
      }
      router.push({
        name: "dataVisualization",
        params: { type: key },
      });
    };
    const chooseBuildingHandler = () => {
      state.changeType = "building";
      state.modalCanCancel = true;
      state.showSwitchModal = true;
    };

    // callback
    const villageChangeHandler = () => {
      state.changeType = "village";
      state.modalCanCancel = true;
      state.showSwitchModal = true;
    };
    const changeDataFromSuccess = (detail) => {
      state.showSwitchModal = false;
      const { current } = detail;
      if (state.changeType == "village") {
        if (current.id == state.currentVillage.id) {
          return;
        }
        setCurrentVillage(current);
      } else {
        if (current.id == state.currentBuilding.id) {
          return;
        }
        setCurrentBuilding(current);
      }
      nextTick(() => {
        initData();
      });
    };
    const handlePreviewModeChange = (checked) => {
      store.dispatch("SetPreviewMode", checked).then(() => {
        state.previewPopVisible = false;
        nextTick(() => {
          initData();
        });
      });
    };

    const getDrawInfo = () => {
      return new Promise((resolve, reject) => {
        request.get("/village", "/project/draw/preview", {}).then((res) => {
          state.isViewClosure = !!res.data_preview_close;
          if (state.isViewClosure) {
            // 预览模式永久关闭了
            store.dispatch("SetPreviewMode", false).then(() => {
              resolve(res)
            });
          } else {
            resolve(res)
          }
        }).catch((err) => {
          reject(err);
        });
      });
    };

    const handlePreviewModeHidden = (hidden) => {
      // state.previewPopVisible = false;
      // message.info("预览模式切换按钮已隐藏，刷新后可重新显示~");
      request.post("/village", "/project/draw/preview", {needMsg: true}).then((res) => {
        message.info(res.msg || '设置成功');
        getDrawInfo().then(() => {
          nextTick(() => {
            initData();
          });
        });
      });
    };

    // request function

    //set function
    const setActiveTab = (tabKey) => {
      if (TAB_KEYS.includes(tabKey)) {
        if (!state.currentVillage.id) {
          initCurrentInfo();
          return;
        }
        state.activeTab = tabKey;
        store.dispatch("SetDataVCurrentMenu", tabKey).then(() => {
          if (!state.loadedTabKeys.length) {
            initMapOrFbx();
            initWebSocket();
            setPreviewAlert();
          } else if (!state.loadedTabKeys.includes(tabKey)) {
            state.socketServe.initMenuSocket();
          }
          state.loadedTabKeys.push(tabKey);
        });
      } else {
        if (state.currentVillage.id) {
          redirectUrl(state.activeTab);
        } else {
          if (state.villageList?.length == 1 && state.changeType == "village") {
            changeDataFromSuccess({current: state.villageList[0]})
          } else {
            state.modalCanCancel = false;
            state.showSwitchModal = true;
          }
        }
      }
    };
    const setCurrentVillage = (village) => {
      store.dispatch("SetCurrentVillage", village);
      state.currentVillage = village;
    };
    const setCurrentBuilding = (building) => {
      store.dispatch("SetCurrentBuilding", building);
      state.currentBuilding = building;
    };
    const setChartPaneShow = () => {
      if (state.showChart) {
        return;
      }
      setTimeout(() => {
        state.showChart = true;
      }, 1000);
    };
    const setPreviewAlert = () => {
      if (previewStatus.value && !store.getters.dataVPreviewAlert) {
        Modal.info({
          title: () => "提示",
          content: () =>
            h("div", {}, [
              h(
                "p",
                "为了大屏的视觉效果，我们默认为您开启了“预览模式”，大屏上的数据都是虚拟提供。您以后可以在页面左下角关闭预览，查看真实数据。"
              ),
              isMobile
                ? null
                : h(
                    "p",
                    { style: "margin-top: 20px; color: rgba(0,0,0,0.5)" },
                    "浏览器分辨率为 1920 * 1080 或以上，视觉效果最佳。"
                  ),
            ]),
          centered: true,
          okText: "好的",
        });
        store.dispatch("SetPreviewModeAlert", true);
      }
    };

    watch(
      () => route.params,
      (params) => {
        if (route.name == "dataVisualization") {
          getDrawInfo().then(() => {
            setActiveTab(params.type);
          });
        }
      }
    );
    watch(
      () => store.getters.resizeTrigger,
      () => {
        common.setPageFontSize();
      }
    );
    watch(
      () => store.getters.dataVClearTrigger,
      () => {
        state.loadedTabKeys = [];
      }
    );
    // watch(previewStatus, (val) => {
    //   setPreviewAlert();
    // });

    // redirect
    const redirectUrl = (type) => {
      let query = route.query;
      router.replace({
        name: "dataVisualization",
        params: { type },
        query,
      });
    };

    // 点击地图上摄像头marker时
    const onMarkerClick = (e) => {
      getMonitorInfo(e.target.id);
    };

    // 点击地图上楼宇marker时
    const onBuildMarkerClick = (e) => {
      onBuildChange(e.target.id);
      showBuildInfoComponent("Section");
    };

    // init and reset

    // 监听选取点拖动
    let onMarkerDragendInit = false;
    let marker = null; // 标注

    const initMapInstance = () => {
      if (mapInstance) {
        return;
      }
      if (!mapInstance) {
        const centerLat = state.currentBuilding.lat || state.currentVillage.lat;
        const centerLng = state.currentBuilding.lng || state.currentVillage.lng;
        const defaultLngLat = new T.LngLat( centerLat, centerLng );

        if (!centerLat || !centerLng) {
          Modal.warning({
            title: () => "提示",
            content: () => "项目位置信息未填写，请先完善后，再回到此页面。",
            okText: "确认",
            onOk: () => {
              // 清空village and build 重新初始化
              store.dispatch("SetCurrentVillage").then(() => {
                initData();
              });
            },
          });
          return;
        }
        // 因为地图和接口都是异步加载，必须要先请求到数据后再初始化地图，否则销毁重新初始化地图时会报错("所传入参数并非TMap.Map的实例")，无法添加marker
        getMonitorList().then(() => {
          mapInstance = new T.Map(state.mapContainer,  {datasourcesControl: true});
          mapInstance.centerAndZoom(defaultLngLat,20);
          //创建缩放平移控件对象,地图缩放控件，可以缩放和移动地图。
          let zoomControl = new T.Control.Zoom();
          mapInstance.addControl(zoomControl);
          state.geocoder = new T.Geocoder();

          getLocationByAddress();

          if (state.monitorDataList.length > 0) {
            state.monitorDataList.forEach((item)=>{
              let point = new T.LngLat(Number(item.lng),Number(item.lat));
              let icon = new T.Icon({
                iconUrl: utils.staticPath + "images/datav/icons/monitorIcon.png",
                iconSize: new T.Point(40, 40),
                iconAnchor: new T.Point(0, 0)
              });
              let marker = new T.Marker(point, {icon: icon})
              mapInstance.addOverLay(marker);
              marker.id = item.id

              let label = new T.Label({
                text: item.text,
                position: marker.getLngLat(),
                offset: new T.Point(0, -30)
              });
              label.setFontColor("#ee6b02")
              label.setBackgroundColor("transparent");
              label.setBorderLine (0)
              label.setFontSize (16)
              mapInstance.addOverLay(label);

              // 为marker添加点击事件的监听器
              marker.addEventListener('click', onMarkerClick);
            })
          }

          // 为楼宇添加markers
          if (state.currentBuilding.id) {
            //初始化marker
            let point = new T.LngLat(Number(state.currentBuilding.lng),Number(state.currentBuilding.lat));
            let icon = new T.Icon({
              iconUrl: utils.staticPath + "images/datav/icons/buildIcon.png",
              iconSize: new T.Point(40, 40),
              iconAnchor: new T.Point(0, 0)
            });
            let marker = new T.Marker(point, {icon: icon})
            mapInstance.addOverLay(marker);
            marker.id = state.currentBuilding.id

            let label = new T.Label({
              text: state.currentBuilding.build_name,
              position: marker.getLngLat(),
              offset: new T.Point(0, -30)
            });
            label.setFontColor("#ee6b02")
            label.setBackgroundColor("transparent");
            label.setBorderLine (0)
            label.setFontSize (16)
            mapInstance.addOverLay(label);

            // 为marker添加点击事件的监听器
            marker.addEventListener('click', onBuildMarkerClick);
          } else if ( state.currentVillage.buildList && state.currentVillage.buildList.length > 0 ) {
            //初始化marker
            let markerArr = [];
            state.currentVillage.buildList.forEach((item) => {
              if (item.lat && item.lng) {
                markerArr.push({
                  id: item.id,
                  text: item.build_name, //文本标注的内容
                  lat : item.lat ,
                  lng : item.lng ,
                });
              }
            });
            if (markerArr.length > 0) {
              markerArr.forEach((item)=>{
                let point = new T.LngLat(Number(item.lng),Number(item.lat));
                let icon = new T.Icon({
                  iconUrl: utils.staticPath + "images/datav/icons/buildIcon.png",
                  iconSize: new T.Point(40, 40),
                  iconAnchor: new T.Point(0, 0)
                });
                let marker = new T.Marker(point, {icon: icon})
                mapInstance.addOverLay(marker);
                marker.id = item.id

                let label = new T.Label({
                  text: item.text,
                  position: marker.getLngLat(),
                  offset: new T.Point(0, -30)
                });
                label.setFontColor("#ee6b02")
                label.setBackgroundColor("transparent");
                label.setBorderLine (0)
                label.setFontSize (16)
                mapInstance.addOverLay(label);

                // 为marker添加点击事件的监听器
                marker.addEventListener('click', onBuildMarkerClick);
              })
            }
          }
          setTimeout(() => {
            setChartPaneShow();
          }, 1000);
        });
      } else {
        setTimeout(() => {
          initMapInstance();
        }, 500);
      }
    };

    const setMarker = (position) => {
      if (!position) {
        // 自己拖动的时候
        position = state.currentAddress.latLng;
      }
      let lngLat = new T.LngLat(
          position.lng,
          position.lat,
      );
      mapInstance.panTo(lngLat);

      //展示标记点
      /*if (marker) {
        marker.setLngLat(lngLat);
      } else {
        //创建标注对象
        marker = new T.Marker(lngLat, {
          draggable: true,
        });
      }
      mapInstance.addOverLay(marker);*/
    };

    const getLocationByAddress = () => {
      // 根据用户选中的来标记地址
      let lngLat = new T.LngLat(
          state.currentVillage.lng,
          state.currentVillage.lat,
      );
      state.geocoder.getLocation(lngLat, getLocationByLatLngResult);
    };

    const getLocationByLatLngResult = (result) => {
      // 根据用户移动的来 设置搜索 和 结果
      let current = {
        name: result.formatted_address,
        hotPointID: result.location.lon,
        latLng: {
          lat: result.location.lat,
          lng: result.location.lon,
        }
      }
      state.addressList = [current];
      state.currentAddress = current;
      setMarker();
    };

    const initMap = () => {
      state.showMapContainer = true;
      let returnConfig = store.getters.returnConfig
      nextTick(() => {
        const mapKey = returnConfig.map && returnConfig.map.tiandutu_map_key
        if(mapKey){
          let script = document.createElement("script");
          script.setAttribute('ignore', 'true');
          script.type = "text/javascript";
          script.src = `https://api.tianditu.gov.cn/api?v=4.0&tk=${mapKey}`;
          document.getElementsByTagName("head")[0].appendChild(script);

          initMapInstance();
        }else {
          setTimeout(() => {
            initMap();
          }, 200);
        }
      });
    };
    const initMapOrFbx = () => {
      // PC端，如果有客户项目图（3D > 2D )，则优先使用客户项目图(移动端无法适配)
      if (state.currentVillage.dimensional_bg_img) {
        if (isMobile.value) {
          console.log("手机端暂不显示鸟瞰图");
        } else {
          state.showCanvasContainer = true;
        }
      } else {
        nextTick(() => {
          initMap();
        });
      }
    };
    const initWebSocket = () => {
      state.socketServe.connect();
    };
    const getCurrentInfo = () => {
      return new Promise((resolve) => {
        store.dispatch("GetCurrentVillageAndBuild").then((res) => {
          state.villageList = res.villageList;
          state.currentVillage = res.currentVillage;
          state.currentBuilding = res.currentBuilding;
          resolve();
        });
      });
    };
    const initCurrentInfo = () => {
      const { type } = route.params;
      getCurrentInfo().then(() => {
        if (!state.currentVillage.id && TAB_KEYS.includes(type)) {
          // to choose village
          redirectUrl("index");
          return;
        }
        if (state.currentVillage.id && type != TAB_KEYS[0]) {
          // redirect to the synthetical page
          redirectUrl(TAB_KEYS[0]);
          return;
        }
        getDrawInfo().then(() => {
          // it must be the synthetical page or untab page
          setActiveTab(type);
        });
      });
    };
    const resetData = () => {
      if (mapInstance) {
        mapInstance = null;
        marker = null;
        mapMonitorMarkers = null;
        mapBuildMarkers = null;
      }
      state.loadedTabKeys = [];
      state.showMapContainer = false;
      state.showCanvasContainer = false;
      customSyntheticalVisibleChange(false);
      state.showChart = false;
    };
    const initData = () => {
      store.dispatch("ResetDataVInfo").then((res) => {
        resetData();
        initCurrentInfo();
      });
    };
    const init = () => {
      window?.microApp?.forceDispatch({
        type: "removeWatermark",
      })
      store.dispatch("SetIsMobile");
      common.setPageFontSize();

      initData();
    };

    init();

    /** -----适配移动端 start -----**/
    const isMobile = computed(() => store.getters.dataVMobile);
    const mobileFit = () => {
      if (isMobile.value) {
        chartBoxStyle.syntheticalLeftBox = {
          left: "1rem",
          right: "1rem",
          width: "auto",
        };
        chartBoxStyle.flowLeftBox = {
          left: "1rem",
          right: "0rem",
          paddingRight: "1.2rem",
          width: "auto",
          overflow: "hidden auto",
        };
      }
    };
    watch(isMobile, () => {
      mobileFit();
    });
    mobileFit();
    /** -----适配移动端 end -----**/

    // 2D鸟瞰图相关
    const showBuildInfoComponent = (type) => {
      let name = `build${type}Visible`;
      state[name] = true;
    };

    const onBuildRealPicClose = () => {
      state.buildRealPicVisible = false;
    };

    const onBuildRichTextClose = () => {
      state.buildRichTextVisible = false;
    };

    const onBuildSectionClose = () => {
      state.buildSectionVisible = false;
    };

    const onBuildChange = (buildId, buildInfo) => {
      if (buildInfo) {
        state.buildInfo = buildInfo;
      }
      if (buildId == state.currentBuilding.id) {
        return;
      }
      let build = state.currentVillage.buildList.find(
        (item) => item.id == buildId
      );
      setCurrentBuilding(build);
    };

    watch(
      () => store.getters.isSyntheticalCustom,
      (val) => {
        if (val === true) {
          if (route.query.type == "edit") {
            state.showCustomSyntheticalEdit = true;
          } else {
            // 有2D鸟瞰图才展示自定义组件
            if (state.currentVillage.dimensional_bg_img) {
              customSyntheticalVisibleChange(true);
            }
          }
        } else if (val === false) {
          if (route.query.type == "edit") {
            state.showCustomSyntheticalEdit = true;
          } else {
            nextTick(() => {
              setChartPaneShow();
            });
          }
        }
      }
    );

    const customSyntheticalVisibleChange = (checked) => {
      state.customSyntheticalVisible = checked;
      state.previewPopVisible = false;
    };

    const getMonitorInfo = (id) => {
      state.currentMonitorVideo = [];
      let params = {
        equipment_id: id,
        village_id: state.currentVillage.id,
        pageSize: 999,
      };
      request
        .get("/work_iot", "/monitor/ptz/list", {
          ...params,
        })
        .then((res) => {
          if (res.data) {
            state.currentMonitorVideo = res.data;
          }
          state.monitorModalVisible = true;
        });
    };

    const onMonitorModalClose = () => {
      state.monitorModalVisible = false;
      state.currentMonitorVideo = [];
    };

    // 获取所有监控设备
    const getMonitorList = () => {
      return new Promise((resolve) => {
        let params = {
          village_id: state.currentVillage.id,
        };
        if (state.currentBuilding.id) {
          params.build_id = state.currentBuilding.id;
        }
        request
          .get("/work_iot", "/monitor/equipment/all", { ...params })
          .then((res) => {
            if (res.result && res.result.length > 0) {
              let markerArr = [];
              res.result.forEach((item) => {
                markerArr.push({
                  id: item.id,
                  text: item.name, //文本标注的内容
                  lat : item.lat ,
                  lng : item.lng ,
                });
              });
              state.monitorDataList = markerArr;
            }
            resolve();
          });
      });
    };

    const isSuperAdmin = computed(
      () =>
        store.getters.userInfo &&
        store.getters.userInfo.level &&
        store.getters.userInfo.level == 99
    );

    return {
      isTabPage,
      previewStatus,
      isMobile,
      chartBoxStyle,
      currentTab,
      ...toRefs(state),
      initData,
      tabChangeHandler,
      villageChangeHandler,
      chooseBuildingHandler,
      changeDataFromSuccess,
      handlePreviewModeChange,
      handlePreviewModeHidden,
      showBuildInfoComponent,
      onBuildRealPicClose,
      onBuildRichTextClose,
      onBuildSectionClose,
      onBuildChange,
      customSyntheticalVisibleChange,

      getMonitorInfo,
      onMonitorModalClose,

      isSuperAdmin,
      setMarker,
      getLocationByAddress,
      getLocationByLatLngResult,
    };
  },
});

// 底部菜单栏
const BOTTOM_TAB_LIST = [
  { key: "synthetical", title: "综合态势" },
  { key: "flow", title: "流量分析" },
  { key: "rentControl", title: "租控管理" },
  { key: "centerControl", title: "智能中控" },
  { key: "security", title: "安防动态" },
];
const TAB_KEYS = [
  "synthetical",
  "flow",
  "rentControl",
  "centerControl",
  "security",
];
</script>

<style lang="less" scoped>
@import "./styles/vars.less";
@import "./styles/common.less";
@shadowColor: rgba(0, 0, 0, 0.6);
.data-visualiztion {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  z-index: 1;
  background-image: url(./images/bg.png);
  background-repeat: no-repeat;
  background-size: 100% 100%;
  font-family: "Noto Sans" "PingFang SC" "Microsoft YaHei";
  color: @lightWhite;
  user-select: none;
  // background: radial-gradient(rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.8) 85%);
  .page-header {
    position: fixed;
    z-index: 30;
    height: @headerHeight;
    top: 0;
    left: 0;
    right: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: @bodyLRPadding @bodyLRPadding 0 @bodyLRPadding;
    pointer-events: none;
  }
  .model-box {
    position: absolute;
    z-index: 10;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: #071420;
    .map-container {
      width: 100%;
      height: 100%;
    }
  }
  .tab-page {
    position: fixed;
    z-index: 20;
    left: 0;
    right: 0;
    top: 0;
    bottom: @tabHeight;
    pointer-events: none;
    .left-chart {
      position: fixed;
      z-index: 31;
      left: @bodyLRPadding;
      top: @headerHeight + 1rem;
      bottom: @tabHeight;
      width: 40rem;
      pointer-events: auto;
    }
    .right-chart {
      position: fixed;
      z-index: 30;
      right: @bodyLRPadding;
      top: @headerHeight + 1rem;
      bottom: @tabHeight;
      width: 40rem;
      pointer-events: auto;
    }
    .full-chart {
      position: fixed;
      z-index: 30;
      left: @bodyLRPadding;
      right: @bodyLRPadding;
      top: @headerHeight + 1rem;
      bottom: @tabHeight;
      pointer-events: auto;
    }
    .left-chart,
    .right-chart,
    .full-chart {
      .hide-scroller-bar {
        width: 100%;
        height: 100%;
        overflow: hidden auto;
      }
    }

    .bottom-chart {
      position: fixed;
      z-index: 30;
      bottom: @tabHeight;
      left: calc(@bodyLRPadding + 40rem);
      width: calc(100% - @bodyLRPadding - @bodyLRPadding - 80rem);
      height: calc(100% - @headerHeight - 1rem - @tabHeight);
      pointer-events: auto;
      padding: 0 1rem;
      pointer-events: none;
    }
  }
  .tl-box-shadow {
    box-shadow: inset 50rem 4rem 20rem 2rem @shadowColor;
  }
  .tlr-box-shadow {
    box-shadow: inset 40rem 0rem 40rem -10rem @shadowColor,
      inset -40rem 0rem 40rem -10rem @shadowColor,
      inset 0rem 10rem 20rem -10rem @shadowColor;
  }

  .page-mask {
    background: rgba(0, 4, 40, 0.85);
    &::before {
      content: "";
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      z-index: -1;
      backdrop-filter: blur(0.3rem);
    }
  }
  // bottom tab
  .tab-list {
    position: fixed;
    z-index: 1000;
    left: 0;
    right: 0;
    bottom: 0;
    height: @tabHeight;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(0, 0, 0, 0.9);
    border-top: 2px solid rgba(255, 255, 255, 0.2);
    font-size: 1.4rem;
    .tab-item {
      width: 100px;
      text-align: center;
      margin: 0;
      color: @lightWhite;
      .item {
        padding: 0.2rem 1rem;
        cursor: pointer;
      }
    }
    .preview-mode {
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      padding: 0 2rem;
      display: flex;
      align-items: center;
    }
    .building-tag {
      position: absolute;
      right: 0;
      top: 0;
      bottom: 0;
      padding: 0 2rem;
      display: flex;
      align-items: center;
    }
  }
}

:deep(.ant-checkbox-wrapper) {
  span {
    padding-right: 0;
  }
}
</style>
